package chris.helloWorld;

import chris.ConFactory;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Recv
 *
 * @author nanxin.chen
 * @since 2017/7/5
 */
public class Recv {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory cf = ConFactory.getConnectionFactory();
        Connection con = cf.newConnection();
        final Channel channel = con.createChannel();

        int prefetchCount = 1;
        channel.basicQos(prefetchCount);

        channel.queueDeclare(Send.QUEUE_NAME, false, false, true, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
                try {
                    Thread.sleep(3000);
                    channel.basicAck(envelope.getDeliveryTag(), false);  //显示调用 ack
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


        };
        // autoAck true if the server should consider messages acknowledged once delivered; false if the server should expect explicit acknowledgements
        // autoAck 为true时, 推给consumer就当做ack了; 为false时需要显示调用 ack
        channel.basicConsume(Send.QUEUE_NAME, false, consumer);
    }
}
